package pl.edu.uj.tcs.blef.protocol;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;

import pl.edu.uj.tcs.blef.server.Client;
import pl.edu.uj.tcs.blef.server.Table;

public class RejectRequestHandler extends AbstractTableHandler {

	public RejectRequestHandler(Table table) {
		super(table);
	}

	@Override
	public void handle(Request request, Socket socket) {
		System.out.println("Handling " + request.message + " request from " + socket.getInetAddress().getHostAddress());
		RejectRequest ctr = (RejectRequest)request;
		if(!table.isOperator(socket)) {
			System.out.println("Unauthorized operator request from socket: " + socket.getInetAddress().getHostAddress());
			try {
				Request r = new UnknownRequestErrorFactory().build(null, new NullRequestHandler());
				r.send(new PrintWriter(socket.getOutputStream()));
			} catch (Exception e){}
		} else {
			if(!table.getIncomingPlayers().contains(new Client(ctr.getPlayerNick(), socket, 1))){
				String[] param = new String[1]; param[0] = ctr.getPlayerNick();
				try {
					Request r = new NoAwaitingPlayerErrorFactory().build(param, new NullRequestHandler());
					r.send(new PrintWriter(socket.getOutputStream()));
				} catch (Exception e){}
			} else {
				Client client = null;
				for(Client c: table.getIncomingPlayers()){
					if(c.getNick().equals(ctr.getPlayerNick())) client = c;
				}
				
				Client newClient = new Client(ctr.getPlayerNick(), client.getSocket(), 1);
				String[] param = new String[1]; param[0] = "OK Rejected player "+ctr.getPlayerNick();
				try {
					Request r = new OKRequestFactory().build(param, new NullRequestHandler());
					r.send(new PrintWriter(socket.getOutputStream()));
				} catch (Exception e){}
				
				try {
					Request r = new RejectedRequestErrorFactory().build(null, new NullRequestHandler());
					r.send(new PrintWriter(newClient.getSocket().getOutputStream()));
				} catch (Exception e){}
				
				try {
					client.getSocket().close();
					table.getIncomingPlayers().remove(client);
				} catch (IOException e) {}
				
			}
		}
	}
}
